﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using Cn.Cellula.Model;
using Cn.Edwon.Web.Session;
using System.IO;
using Cn.Edwon.Spring;
using Cn.Edwon.Biz;
using Cn.Cellula.Biz.Port;
using Cn.Edwon.Web;
using Cn.Cellula.Biz;
using System.Reflection;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using Cn.Cellula.Model.Product;
using Cn.Cellula.Model.Content;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Cn.Cellula.Model.System;
using Cn.Cellula.Model.Security;
using Cn.Edwon.Web.Ac;
using Cn.Edwon.Util;

namespace Cn.Cellula.Client {
    public class QueryAtlItem {
        private String _AtlKey;
        public String AtlKey {
            set { _AtlKey = value; }
            get { return _AtlKey; }
        }
        private String _AtlData;
        public String AtlData {
            set { _AtlData = value; }
            get { return _AtlData; }
        }
    }
    public class ClientBiz {
        private static Common.Logging.ILog log = Common.Logging.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public const String VALIDATE_CODE_SESSION_KEY = "validate_code";
        public const String GRIDVIEW_ROW_CHECKBOX_ID = "cbxRow";
        public const Int32 PRODUCT_QUERY_LIST_PAGESIZE = 20;
        public static String AdminDefaultUrl {
            get { return ClientHelper.RootUrl + "Admin/Default.aspx"; }
        }

        #region 上传文件管理
        public static Boolean CheckUploadFile(String rFileExtName,String rPattern){
            if (String.IsNullOrEmpty(rFileExtName)) return false;
            if (String.IsNullOrEmpty(rPattern)) return true;
            rFileExtName = rFileExtName.ToLower();
            rPattern = rPattern.ToLower();
            if (rFileExtName.IndexOf(".") == -1) rFileExtName = "." + rFileExtName;
            return (("|" + rPattern).IndexOf("|" + rFileExtName) != -1);
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="rFile"></param>
        /// <param name="rModelName"></param>
        /// <param name="rModelKey"></param>
        /// <param name="rOwnerKey"></param>
        /// <param name="rActor"></param>
        /// <returns></returns>
        public static void UploadFile(ref TUploadFileEO eo,HttpPostedFile rFile, string rModelName, string rModelKey,String rOwnerKey,ISessActor rActor) {
            eo.OwnerKey = rOwnerKey;
            eo.SrcName = rFile.FileName;
            eo.SrcName = eo.SrcName.Replace("\\", "/");
            eo.SrcName = eo.SrcName.Substring(eo.SrcName.LastIndexOf("/") + 1);
            eo.ExtName = System.IO.Path.GetExtension(rFile.FileName);
            if (String.IsNullOrEmpty(eo.ExtName)) {
                throw new Exception("无法确定的文件类型");
            }
            eo.ExtName = eo.ExtName.ToLower();
            eo.SrcName = eo.SrcName.Replace(eo.ExtName, "");
            eo.FileTitle = eo.SrcName;
            if (String.IsNullOrEmpty(rModelName)) {
                throw new Exception("没有设定Model Name");
            }
            eo.ModelName = rModelName;
            if (String.IsNullOrEmpty(rModelKey)) {
                throw new Exception("没有设定Model Key");
            }
            eo.ModelKey = rModelKey;
            eo.FileWeight = rFile.ContentLength;
            eo.FileKey = Guid.NewGuid().ToString();
            eo.UploadDate = DateTime.Now;
            eo.UploadMan = (rActor == null) ? "guest" : rActor.ID;
            //保存绝对地址，或者相对于根的地址
            eo.FilePath = SiteConfig.Upload.UploadForder + rOwnerKey + "/" + eo.ModelName + "/" + eo.FileKey + eo.ExtName;
            if (!Directory.Exists(SiteConfig.Upload.UploadPath + rOwnerKey + "/" + eo.ModelName)) {
                Directory.CreateDirectory(SiteConfig.Upload.UploadPath + rOwnerKey + "/" + eo.ModelName);
                log.Debug("Create dir:" + SiteConfig.Upload.UploadPath + rOwnerKey + "/" + eo.ModelName);
            }
            //如果是图片，生成缩略图
            if (CheckUploadFile(eo.ExtName, SiteConfig.Upload.UploadImagePattern)) {
                rFile.SaveAs(ClientHelper.RootPath + eo.FilePath);
                log.Debug("Save image:" + ClientHelper.RootPath + eo.FilePath);
                System.Drawing.Image img = System.Drawing.Image.FromStream(rFile.InputStream);
                int ow = img.Width;
                int oh = img.Height;
                eo.FileHeight = oh;
                eo.FileWidth = ow;
                //eo.ExtName本身是以点(.)开头的
                if (eo.FileWeight<10240) {//小尺寸图或者不足10K的图
                    eo.Thumbnail = SiteConfig.Upload.UploadForder + rOwnerKey + "/" + eo.ModelName + "/" + eo.FileKey + ".s"+eo.ExtName;
                    rFile.SaveAs(ClientHelper.RootPath + eo.Thumbnail);
                    log.Debug("Save Thumbnail:" + ClientHelper.RootPath + eo.Thumbnail);
                } else {
                    int dw, dh;
                    if (ow > oh) {//橫版
                        dw = Convert.ToInt32(SiteConfig.Upload.ThumbnailMaxWidth);
                        dh = Convert.ToInt32((dw * oh) / ow);
                    } else {
                        dh = Convert.ToInt32(SiteConfig.Upload.ThumbnailMaxHeight);
                        dw = Convert.ToInt32((dh * ow) / oh);
                    }
                    System.Drawing.Image thumbnail = new System.Drawing.Bitmap(dw, dh);
                    //System.Drawing.Image thumbnail = img.GetThumbnailImage(dw, dh, null, System.IntPtr.Zero);
                    Graphics g = Graphics.FromImage(thumbnail);
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.High;
                    g.Clear(Color.White);
                    g.DrawImage(img, new Rectangle(0, 0, dw, dh), new Rectangle(0, 0, ow, oh), GraphicsUnit.Pixel);
                    g.Dispose();
                    g = null;
                    if (eo.ExtName == ".png") {
                        eo.Thumbnail = SiteConfig.Upload.UploadForder + rOwnerKey + "/" + eo.ModelName + "/" + eo.FileKey + ".s.jpg";
                        thumbnail.Save(ClientHelper.RootPath + eo.Thumbnail, ImageFormat.Jpeg);
                    } else {
                        eo.Thumbnail = SiteConfig.Upload.UploadForder + rOwnerKey + "/" + eo.ModelName + "/" + eo.FileKey + ".s.jpg";
                        thumbnail.Save(ClientHelper.RootPath + eo.Thumbnail, ImageFormat.Jpeg);
                    }
                    log.Debug("Save Thumbnail:" + ClientHelper.RootPath + eo.Thumbnail);
                    thumbnail.Dispose();
                    img.Dispose();
                    thumbnail = null;
                    img = null;
                }

            } else if (CheckUploadFile(eo.ExtName, SiteConfig.Upload.UploadFilePattern)) {
                rFile.SaveAs(ClientHelper.RootPath + eo.FilePath);
                log.Debug("Save file:" + ClientHelper.RootPath + eo.FilePath);
                eo.Thumbnail = "";
            } else {
                throw new Exception("非法的文件格式");
            }
            rFile = null;
        }
        public static TUploadFileEO ReUpdateFile(String rFileKey, HttpPostedFile rFile, string rModelName, string rModelKey, String rOwnerKey, ISessActor rActor) {
            TUploadFileEO eo = BizFactory.Get<IBiz>().Load<TUploadFileEO>(rFileKey);

            if (eo.OwnerKey != rOwnerKey) {
                log.Error("更新文件时错误：不匹配的ownerkey");
                throw new Exception("属主权限错误");
            }
            if (eo.ModelName != rModelName) {
                log.Error("更新文件时错误：不匹配的modelname");
                throw new Exception("模块权限错误");
            }
            if (eo.ModelKey != rModelKey) {
                log.Error("更新文件时错误：不匹配的modelKey");
                throw new Exception("对象权限错误");
            }
            eo.SrcName = rFile.FileName;
            eo.SrcName = eo.SrcName.Replace("\\", "/");
            eo.SrcName = eo.SrcName.Substring(eo.SrcName.LastIndexOf("/") + 1);
            eo.ExtName = System.IO.Path.GetExtension(rFile.FileName);
            if (String.IsNullOrEmpty(eo.ExtName)) {
                throw new Exception("无法确定的文件类型");
            }
            eo.ExtName = eo.ExtName.ToLower();
            eo.SrcName = eo.SrcName.Replace(eo.ExtName, "");
            eo.FileWeight = rFile.ContentLength;
            eo.UploadDate = DateTime.Now;
            eo.UploadMan = (rActor == null) ? "guest" : rActor.ID;
            String fileDir = SiteConfig.Upload.UploadForder + rOwnerKey + "/" + eo.ModelName + "/";
            String savePath = ClientHelper.RootPath + fileDir;
            if (!Directory.Exists(savePath)) {
                Directory.CreateDirectory(savePath);
            }
            //如果是图片，生成缩略图
            if (CheckUploadFile(eo.ExtName, SiteConfig.Upload.UploadImagePattern)) {
                rFile.SaveAs(savePath + eo.FileKey + eo.ExtName);
                log.Debug("ReSave image:" + ClientHelper.RootPath + eo.FilePath);
                System.Drawing.Image img = System.Drawing.Image.FromStream(rFile.InputStream);
                int ow = img.Width;
                int oh = img.Height;
                eo.FileHeight = oh;
                eo.FileWidth = ow;
                if (ow < SiteConfig.Upload.ThumbnailMaxWidth && oh < SiteConfig.Upload.ThumbnailMaxHeight) {
                    rFile.SaveAs(savePath + "/" + eo.FileKey + ".s" + eo.ExtName);
                } else {
                    int dw, dh;
                    if (ow > oh) {//橫版
                        dw = Convert.ToInt32(SiteConfig.Upload.ThumbnailMaxWidth);
                        dh = Convert.ToInt32((dw * oh) / ow);
                    } else {
                        dh = Convert.ToInt32(SiteConfig.Upload.ThumbnailMaxHeight);
                        dw = Convert.ToInt32((dh * ow) / oh);
                    }
                    System.Drawing.Image thumbnail = new Bitmap(dw, dh);
                    Graphics g = Graphics.FromImage(thumbnail);
                    g.DrawImage(img, new Rectangle(0, 0, dw, dh), new Rectangle(0, 0, ow, oh), GraphicsUnit.Pixel);
                    g.Dispose();
                    thumbnail.Save(savePath + eo.FileKey + ".s" + eo.ExtName);
                    thumbnail.Dispose();
                    img.Dispose();
                }
                eo.Thumbnail = fileDir + eo.FileKey + ".s" + eo.ExtName;

            } else if (CheckUploadFile(eo.ExtName, SiteConfig.Upload.UploadFilePattern)) {
                rFile.SaveAs(savePath + eo.FileKey + eo.ExtName);
                log.Debug("ReSave file:" + ClientHelper.RootPath + eo.FilePath);
                eo.Thumbnail = "";
            } else {
                throw new Exception("非法的文件格式");
            }
            rFile = null;
            return eo;
        }
        public static int DeleteFileByModelKey(String rModelKey,String rOwnerKey) {
            int count = 0;
            IUploadFileBiz biz = BizFactory.Get<IUploadFileBiz>();
            IList<TUploadFileEO> list = biz.LoadByModelKey(rModelKey);
            foreach (TUploadFileEO eo in list) {
                if (eo.OwnerKey != rOwnerKey) continue;
                if (File.Exists(ClientHelper.RootPath + eo.FilePath))
                    File.Delete(ClientHelper.RootPath + eo.FilePath);
                if (File.Exists(ClientHelper.RootPath + eo.Thumbnail))
                    File.Delete(ClientHelper.RootPath + eo.Thumbnail);
                biz.Delete<TUploadFileEO>(eo.FileKey);
                count++;
            }
            return count;
        }
        #endregion

        #region 绑定基础数据
        /// <summary>
        /// 绑定基础数据列表
        /// </summary>
        /// <param name="rDdl"></param>
        /// <param name="rCodeTypeKey"></param>
        public static void BindCodeList(ref DropDownList rDdl, String rCodeTypeKey,Boolean rSelected,String rDefaultText) {
            rDdl.DataValueField = "CodeKey";
            rDdl.DataTextField = "CodeName";
            rDdl.DataSource = BizFactory.Get<ICodeBiz>().LoadCodeByType(rCodeTypeKey);
            rDdl.DataBind();
            if (rSelected) {
                if(rDefaultText!=null)
                    rDdl.SelectedValue = rDefaultText;
            }else{
                rDdl.Items.Insert(0, new ListItem(rDefaultText, ""));
            }
        }
        /// <summary>
        /// 绑定基础数据列表
        /// </summary>
        /// <param name="rDdl"></param>
        /// <param name="rCodeTypeKey"></param>
        public static void BindCodeList(ref CheckBoxList rCbl, String rCodeTypeKey, Boolean rSelected, String rDefaultText) {
            rCbl.DataValueField = "CodeKey";
            rCbl.DataTextField = "CodeName";
            rCbl.DataSource = BizFactory.Get<ICodeBiz>().LoadCodeByType(rCodeTypeKey);
            rCbl.DataBind();
            if (rSelected) {
                if (rDefaultText != null)
                    rCbl.SelectedValue = rDefaultText;
            } else {
                rCbl.Items.Insert(0, new ListItem(rDefaultText, ""));
            }
        }
        /// <summary>
        /// 绑定基础数据列表
        /// </summary>
        /// <param name="rDdl"></param>
        /// <param name="rCodeTypeKey"></param>
        public static void BindCodeList(ref RadioButtonList rRbl, String rCodeTypeKey, Boolean rSelected, String rDefaultText) {
            rRbl.DataValueField = "CodeKey";
            rRbl.DataTextField = "CodeName";
            rRbl.DataSource = BizFactory.Get<ICodeBiz>().LoadCodeByType(rCodeTypeKey);
            rRbl.DataBind();
            if (rSelected) {
                if (rDefaultText != null)
                    rRbl.SelectedValue = rDefaultText;
            } else {
                rRbl.Items.Insert(0, new ListItem(rDefaultText, ""));
            }

        }

        public static void BindYNList(ref CheckBoxList rCtrol, Boolean rSelected, String rDefaultText) {
            rCtrol.Items.Clear();
            rCtrol.Items.Add(new ListItem("是","1"));
            rCtrol.Items.Add(new ListItem("否","0"));
            if (!rSelected) {
                rCtrol.Items.Insert(0, new ListItem(rDefaultText, ""));
            } else {
                rCtrol.SelectedIndex = 1;
            }
        }
        public static void BindYNList(ref RadioButtonList rCtrol, Boolean rSelected, String rDefaultText) {
            rCtrol.Items.Clear();
            rCtrol.Items.Add(new ListItem("是", "1"));
            rCtrol.Items.Add(new ListItem("否", "0"));
            if (!rSelected) {
                rCtrol.Items.Insert(0, new ListItem(rDefaultText, ""));
            } else {
                rCtrol.SelectedIndex = 1;
            }
        }
        public static void BindYNList(ref DropDownList rCtrol, Boolean rSelected, String rDefaultText) {
            rCtrol.Items.Clear();
            rCtrol.Items.Add(new ListItem("是", "1"));
            rCtrol.Items.Add(new ListItem("否", "0"));
            if (!rSelected) {
                rCtrol.Items.Insert(0, new ListItem(rDefaultText, ""));
            } else {
                rCtrol.SelectedIndex = 1;
            }
        }
        #endregion

        #region 其他方法
        /// <summary>
        /// 对密码进行加密编码
        /// </summary>
        /// <param name="rPwd"></param>
        /// <returns></returns>
        public static String Md5(String rPwd) {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(rPwd, "md5");
        }

        public static Int32 GetPageCount(Int32 rTotalCount, Int32 rPageSize) {
            Int32 PageCount = (rTotalCount % rPageSize == 0) ? (rTotalCount / rPageSize) : Convert.ToInt32(Math.Ceiling(rTotalCount / rPageSize * 1.0));
            if (PageCount <= 0)
                PageCount = 1;
            return PageCount;
        }

        public static Int32 FixCurrentPage(Int32 rTotalCount, Int32 rPageSize, Int32 rCurrentPage) {
            Int32 PageCount = GetPageCount(rTotalCount, rPageSize);
            if (rCurrentPage < 1)
                return 1;
            else if (rCurrentPage > PageCount)
                return PageCount;
            else
                return rCurrentPage;
        }

        public static String EncodeJsString(String rStr) {
            if (String.IsNullOrEmpty(rStr)) {
                return "";
            } else {
                rStr = rStr.Replace("\"", "");
                rStr = rStr.Replace("'", "");
                return rStr;
            }
        }
        /// <summary>
        /// 构造翻页字符串
        /// </summary>
        /// <param name="rTotalCount"></param>
        /// <param name="rPageSize"></param>
        /// <param name="rUrl"></param>
        /// <param name="rCurrentPage"></param>
        /// <returns></returns>
        public static String BuildPagerStr(Int32 rTotalCount, Int32 rPageSize, String rUrl, Int32 rCurrentPage) {
            Int32 PageCount = GetPageCount(rTotalCount, rPageSize);
            rCurrentPage = FixCurrentPage(rTotalCount, rPageSize, rCurrentPage);
            Int32 nextPage = (rCurrentPage < PageCount) ? (rCurrentPage + 1) : rCurrentPage;
            String url = (rUrl.IndexOf("?") == -1) ? (rUrl + "?page=") : (rUrl + "&page=");
            StringBuilder sb = new StringBuilder();
            sb.Append("<table class=\"pager_number_table\" cellspacing=\"2\" cellpadding=\"0\"><tr>");
            if (rCurrentPage > 1) {
                sb.Append("<td class=\"pager_number_prev\"><a href=\"" + url + (rCurrentPage - 1) + "\">上一页</a></td>");
            }
            if (PageCount <= 10) {
                for (int i = 1; i <= PageCount; i++) {
                    if (i == rCurrentPage)
                        sb.Append("<td class=\"pager_number_item_a\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                    else
                        sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                }
            } else {//超过10页
                if (rCurrentPage < 5) {
                    for (int i = 1; i <= 5; i++) {
                        if (i == rCurrentPage)
                            sb.Append("<td class=\"pager_number_item_a\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                        else
                            sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                    }
                    sb.Append("<td class=\"pager_number_txt\">...</td>");
                    sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (PageCount) + "\">" + PageCount + "</a></td>");
                } else if (rCurrentPage > (PageCount - 4)) {
                    sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + "1\">1</a></td>");
                    sb.Append("<td>...</td>");
                    for (int i = (PageCount - 4); i <= PageCount; i++) {
                        if (i == rCurrentPage)
                            sb.Append("<td class=\"pager_number_item_a\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                        else
                            sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                    }
                } else {
                    sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + "1\">1</a></td>");
                    sb.Append("<td class=\"pager_number_txt\">...</td>");
                    for (int i = rCurrentPage - 2; i <= rCurrentPage + 2; i++) {
                        if (i == rCurrentPage)
                            sb.Append("<td class=\"pager_number_item_a\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                        else
                            sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (i) + "\">" + (i) + "</a></td>");
                    }
                    sb.Append("<td class=\"pager_number_txt\">...</td>");
                    sb.Append("<td class=\"pager_number_item\"><a href=\"" + url + (PageCount) + "\">" + PageCount + "</a></td>");

                }
            }
            if (rCurrentPage < PageCount) {
                sb.Append("<td class=\"pager_number_next\"><a href=\"" + url + (nextPage) + "\">下一页</a></td>");
            }
            sb.Append("<td class=\"pager_number_total_info\">共" + PageCount + "页</td>");
            //sb.Append("<td>到第<input type=\"text\" value=\"" + nextPage + "\" id=\"txt_PagerGoto\" />页</td>");
            sb.Append("</tr></table>");
            return sb.ToString();
        }

        public static String ParseCoverPath(String rSrc,String rDef){
            return (String.IsNullOrEmpty(rSrc)) ? rDef : rSrc;
        }
        public static String ParseCoverPath(Object rSrc, String rDef) {
            return (rSrc != null && rSrc.ToString() != "") ? rSrc.ToString() : rDef;
        }
        #endregion

        #region Cookie
        public class CookieItem {
            private String _UserKey;
            public String UserKey {
                set { _UserKey = value; }
                get { return _UserKey; }
            }
            private String _Password;
            public String Password {
                set { _Password = value; }
                get { return _Password; }
            }
            private String _IP;
            public String IP {
                set { _IP = value; }
                get { return _IP; }
            }
        }
        public class Cookie {
            public const string COOKIE_NAME = "cookie_cn_cellula";
            public const string COOKIE_SECRET_KEY = "as&2a!@3";
            private static HttpCookie GetWriteCookie(ISessActor rActor, String rIP) {
                if (rActor == null) return null;
		        HttpCookie _Cookie = new HttpCookie(Cookie.COOKIE_NAME);
                _Cookie.Values.Add("uid", rActor.ID);
                _Cookie.Values.Add("chkstr", Md5(rActor.Password+COOKIE_SECRET_KEY));
                _Cookie.Values.Add("ip", rIP);
                _Cookie.Values.Add("epr", DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd hh:mm:ss"));
                _Cookie.Expires = DateTime.Now.AddMonths(1);
                return _Cookie;
            }
            public static void Append(ISessActor rActor,String rIP,HttpResponse rResponse){
                log.Debug("Appending cookie");
                HttpCookie _cookie = GetWriteCookie(rActor, rIP);
                if (_cookie != null) {
                    rResponse.AppendCookie(_cookie);
                    log.Debug("Cookie: Appended,Expires:" + _cookie.Expires.ToString());
                } else {
                    log.Debug("Cookie is null");
                }
                log.Debug("Appending end");
            }
            public static void AbateCookie(HttpRequest rRequest,HttpResponse rResponse) {
                log.Debug("Abating cookie");
                HttpCookie cookie = rRequest.Cookies[ClientBiz.Cookie.COOKIE_NAME];
                if (cookie != null) {
                    log.Debug("Abate cookie : " + ClientBiz.Cookie.COOKIE_NAME);
                    cookie.Values["uid"] = "-1";
                    cookie.Values["epr"] = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh:mm:ss");
                    cookie.Expires = DateTime.Now.AddDays(-1); ;
                    rResponse.AppendCookie(cookie);
                } else {
                    log.Debug("Cookie is null");
                }
                log.Debug("Abating end");
            }
            public static CookieItem Load(HttpCookie rCookie, String rIP) {
                log.Debug("Loading Cookie");
                //expires:" + expires.ToString());
                if (null != rCookie) {
                    try {
                        DateTime expires = rCookie.Expires;
                        try {
                            expires = Convert.ToDateTime(rCookie.Values["epr"]);
                        } catch {
                            log.Error("Exception on convert epr to datetime");
                        }
                        log.Debug("Cookie expires:" + expires.ToString());
                        if (DateTime.Compare(DateTime.Now, expires) < 0) {
                            log.Debug("Cookie is in expires,create a new CookieItem");
                            CookieItem co = new CookieItem();
                            co.IP = rCookie.Values["ip"];
                            co.Password = rCookie.Values["chkstr"];
                            co.UserKey = rCookie.Values["uid"];
                            return co;
                        }
                    } catch (Exception ex) {
                        log.Error("Loading exception:" + ex.Message);
                    }
                } else {
                    log.Debug("Cookie is null");
                }
                log.Debug("Loadding end");
                return null;
            }
        }
        #endregion

        #region SiteConfig 设置函数
        #region WebConfig方式
        public static void SetAppIntItem(ref XmlDocument rDoc, String rKey, String rValue, Int32 rDefault) {
            Int32 val = -1;
            try {
                val = Convert.ToInt32(rValue);
            } catch {
                val = rDefault;
            }
            SetAppItem(ref rDoc, rKey, val.ToString());
        }
        public static void SetAppItem(ref XmlDocument rDoc, String rKey, String rValue) {
            if (String.IsNullOrEmpty(rKey)) {//键值不能为空
                return;
            }
            XmlNode appNode = rDoc.SelectSingleNode("//appSettings");
            if (appNode == null) {
                appNode = rDoc.CreateElement("appSettings");
                rDoc.DocumentElement.AppendChild(appNode);
            }
            XmlNode n = appNode.SelectSingleNode("add[@key='" + rKey + "']");
            if (n == null) {
                n = rDoc.CreateElement("add");
                XmlAttribute attr = rDoc.CreateAttribute("key");
                attr.Value = rKey;
                n.Attributes.Append(attr);
                attr = rDoc.CreateAttribute("value");
                attr.Value = rValue;
                n.Attributes.Append(attr);
                appNode.AppendChild(n);
            }
            if (n.Attributes["value"] == null) {
                XmlAttribute attr = rDoc.CreateAttribute("value");
                attr.Value = rValue;
                n.Attributes.Append(attr);
            } else {
                n.Attributes["value"].Value = rValue;
            }
        }
        public static String GetAppItem(ref XmlDocument rDoc, String rKey) {
            return GetAppItem(ref rDoc, rKey, "");
        }
        public static String GetAppItem(ref XmlDocument rDoc, String rKey, String rDefault) {
            if (rDefault == null) rDefault = "";
            XmlNode appNode = rDoc.SelectSingleNode("//appSettings");
            if (appNode == null) {
                return rDefault;
            }
            XmlNode n = appNode.SelectSingleNode("add[@key='" + rKey + "']");
            if (n == null) {
                return rDefault;
            }
            return n.Attributes["value"].Value;
        }
        #endregion
        #region 数据库方式
        /*---- 数据方式
        public static void SetAppItem(String rKey,String rValue,String rName,String rDesc) {
            IBiz biz = BizFactory.Get<IBiz>();
            try {
                TSysSiteConfigEO eo = biz.Load<TSysSiteConfigEO>(rKey);
                if (!String.IsNullOrEmpty(rDesc)) {
                    eo.CfgDescription = rDesc;
                }
                if (!String.IsNullOrEmpty(rValue)) {
                    eo.CfgValue = rValue;
                }
                biz.Update<TSysSiteConfigEO>(eo);
            } catch {
                TSysSiteConfigEO eo = new TSysSiteConfigEO();
                eo.CfgKey = rKey;
                eo.CfgName = rName;
                eo.CfgValue = rValue;
                eo.CfgDescription = rDesc;
                biz.Save<TSysSiteConfigEO>(eo);
            }


        }
        public static String GetAppItem(IList<TSysSiteConfigEO> rList,String rKey) {
            if (rList != null && rList.Count > 0) {
                foreach (TSysSiteConfigEO eo in rList) {
                    if (eo.CfgKey == rKey)
                        return eo.CfgValue;
                }
            }
            return "";
        }
        public static void InitSiteConfig() {
            IList<TSysSiteConfigEO> list = BizFactory.Get<IBiz>().LoadAll<TSysSiteConfigEO>();
            SiteConfig.Copyright = GetAppItem(list, AppSettingsKey.SysCopyright);
            SiteConfig.LogoUrl = GetAppItem(list, AppSettingsKey.SysLogoUrl);
            SiteConfig.PageTitle = GetAppItem(list, AppSettingsKey.SysPageTitle);
            String ProductNoAutoStr = GetAppItem(list, AppSettingsKey.ProductNoAuto);
            SiteConfig.ProductNoAuto = (ProductNoAutoStr == "1");
            SiteConfig.SiteName = GetAppItem(list, AppSettingsKey.SysSiteName);
            try {
                String regCheckVal = GetAppItem(list, AppSettingsKey.UserRegCheck);
                SiteConfig.UserRegCheck = (Cn.Cellula.Website.SiteConfig.RegisterCheck)Enum.Parse(typeof(Cn.Cellula.Website.SiteConfig.RegisterCheck), regCheckVal);
            } catch {
                SiteConfig.UserRegCheck = Cn.Cellula.Website.SiteConfig.RegisterCheck.None;
            }
            try {
                SiteConfig.ThumbnailMaxHeight = Convert.ToInt32(GetAppItem(list, AppSettingsKey.ThumbnailMaxHeight));
            } catch {
                SiteConfig.ThumbnailMaxHeight = 100;
            }
            try {
                SiteConfig.ThumbnailMaxWidth = Convert.ToInt32(GetAppItem(list, AppSettingsKey.ThumbnailMaxWidth));
            } catch {
                SiteConfig.ThumbnailMaxWidth = 100;
            }
            SiteConfig.UploadFilePattern = GetAppItem(list, AppSettingsKey.SysUploadFilePattern);
            SiteConfig.UploadImagePattern = GetAppItem(list, AppSettingsKey.SysUploadImagePattern);
            String path = FixFolderName(GetAppItem(list, AppSettingsKey.SysUploadPath));
            if (path.IndexOf(":") != -1) {
                SiteConfig.UploadPath = path;
            } else {
                SiteConfig.UploadPath = ClientHelper.RootPath + path;
            }

            path = FixFolderName(GetAppItem(list, AppSettingsKey.SysUploadUrl));
            if (path.IndexOf(":") != 1) {
                SiteConfig.UploadUrl = path;
            } else {
                SiteConfig.UploadUrl = ClientHelper.RootUrl + path;
            }
            SiteConfig.UserLoginProperty = GetAppItem(list, AppSettingsKey.UserLoginProperty);
            SiteConfig.UserRoleDefault = GetAppItem(list, AppSettingsKey.UserRoleDefault);
        }
        public static String FixFolderName(String rDir) {
            if (String.IsNullOrEmpty(rDir)) return "";
            rDir = rDir.Replace("\\", "/");
            if (rDir.IndexOf("/") == -1 || rDir.Substring(rDir.LastIndexOf("/")) != "/") {
                rDir += "/";
            }
            return rDir;
        }
         * */
        #endregion
        #endregion

        #region 产品相关

        public static String ParseAtlItemList2String(IList<QueryAtlItem> rList) {
            StringBuilder sb = new StringBuilder();
            for (int i=0;i<rList.Count;i++){
                QueryAtlItem ai = rList[i];
                sb.Append("|"+ai.AtlKey + "," + ai.AtlData);
            }
            return sb.ToString();
        }
        public static IList<QueryAtlItem> ParseAtlString2ItemList(String rAtlString) {
            IList<QueryAtlItem> list = new List<QueryAtlItem>();
            if (!String.IsNullOrEmpty(rAtlString)) {
                try {
                    String[] items = rAtlString.Split('|');
                    foreach (String i in items) {
                        if (i.IndexOf(",") == -1) continue;
                        String[] val = i.Split(',');
                        QueryAtlItem ai = new QueryAtlItem();
                        ai.AtlData = val[1];
                        ai.AtlKey = val[0];
                        list.Add(ai);
                    }
                } catch(Exception ex) {
                    log.Error(ex.Message);
                }
            }
            return list;
        }

        /// <summary>
        /// 根据分类，获取产品查询面板的HTML代码
        /// </summary>
        /// <param name="rCategoryKey"></param>
        /// <returns></returns>
        public static string LoadAtlQueryPanelByCategory(string rCategoryKey,String rAtlQuery) {
            IProductBiz biz = BizFactory.Get<IProductBiz>();
            IList<VProductAtlEO> list = biz.LoadProductAtlByCategory(rCategoryKey);
            IList<VProductAtlOptionsEO> opts = biz.LoadProductOptByCategory(rCategoryKey);
            StringBuilder sbSelected = new StringBuilder();
            sbSelected.Append("<table><tr>");
            if (!String.IsNullOrEmpty(rAtlQuery)) {
                sbSelected.Append("<td>您已选择：</td>");
            }
            sbSelected.Append("<td>");
            StringBuilder sb = new StringBuilder();
            sb.Append("<table class=\"product_query_panel_table\" cellspacing=\"0\" cellpadding=\"0\">");
            Int32 repeatColumn = 6;
            String[] atlItem = null;
            String[] atlList = null;
            foreach (VProductAtlEO atl in list) {
                if (!String.IsNullOrEmpty(rAtlQuery) && rAtlQuery.IndexOf(atl.AtlKey) != -1) { //已经选择了某个Atl
                    atlList = rAtlQuery.Split('|');
                    for (var i = 0; i < atlList.Length; i++) {
                        atlItem = atlList[i].Split(',');
                        if (atlItem != null && atlItem.Length>1 && atlItem[0] == atl.AtlKey) {
                            sbSelected.Append("<div  class=\"product_query_panel_item_selected\"><a href=\"javascript:productQuery.removeAtl('" + atl.AtlKey + "','" + atlItem[1] + "');\">" + atl.AtlName + "：" + atlItem[1] + "<span class=\"product_query_panel_item_close\">X</span></a></div>");
                            break;
                        }
                    }
                }else if (atl.IsQueriable == 1) {//是否用来查询的属性
                    sb.Append("<tr>");
                    sb.Append("<td class=\"product_query_panel_item_t\">" + atl.AtlName + "：</td>");
                    Int32 optCount = 0;
                    foreach (VProductAtlOptionsEO opt in opts) {
                        if (atl.AtlKey == opt.AtlKey) {
                            if (optCount != 0 && (optCount % repeatColumn == 0)) {
                                sb.Append("</tr><tr><td></td>");
                            }
                            sb.Append("<td class=\"product_query_panel_item_v\">");
                            sb.Append("<a href=\"javascript:productQuery.selectAtl('"+atl.AtlKey+"','"+opt.OptValue+"');\" >" + opt.OptText + "</a>");
                            sb.Append("</td>");
                            optCount++;
                        }
                    }
                    sb.Append("</tr>");
                }
            }
            sb.Append("</table>");
            sbSelected.Append("</td></tr></table>");
            sbSelected.Append(sb.ToString());
            return sbSelected.ToString();
        }
        /// <summary>
        /// 获取产品扩展属性的编辑面板
        /// </summary>
        /// <param name="rCategoryKey"></param>
        /// <param name="rProductKey"></param>
        /// <returns></returns>
        public static string LoadProductAtlEditForm(String rCategoryKey, String rProductKey) {
            IProductBiz biz = BizFactory.Get<IProductBiz>();
            IList<VProductAtlEO> list = biz.LoadProductAtlByCategory(rCategoryKey);

            String hql = "from TProductAtlOptionsEO eo ";
            hql += " order by eo.OrderNumber desc ";
            IList<TProductAtlOptionsEO> optList = biz.Find<TProductAtlOptionsEO>(hql);

            IList<TProductAtlDataEO> dataList = new List<TProductAtlDataEO>();
            if (!String.IsNullOrEmpty(rProductKey)) {
                hql = " from TProductAtlDataEO eo where eo.ProductKey='" + rProductKey + "' ";
                dataList = biz.Find<TProductAtlDataEO>(hql);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"product_atl_form_table\">");
            foreach (VProductAtlEO eo in list) {
                sb.Append("<tr>");
                sb.Append("<td class=\"product_atl_form_name\">" + eo.AtlName + "：</td>");
                sb.Append("<td class=\"product_atl_form_field\">");
                String val = eo.DefaultValue;
                foreach (TProductAtlDataEO data in dataList) {
                    if (data.AtlKey == eo.AtlKey) {
                        val = data.DataValue;
                    }
                }
                String id_name_val = " id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" value=\"" + val + "\" ";
                String name = " name=\"" + eo.AtlKey + "\" ";
                if (eo.FieldType == CodeTypeDef.FormField.CheckBox) {
                    sb.Append("<input type=\"checkbox\" " + name + " value=\"\" />" + TxtDef.DDLTextEmpty + "");
                    foreach (TProductAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<input type=\"checkbox\" " + name + " value=\"" + opt.OptValue + "\" checked=\"checked\" />" + opt.OptText + "");
                            } else {
                                sb.Append("<input type=\"checkbox\" " + name + " value=\"" + opt.OptValue + "\" />" + opt.OptText + "");
                            }
                        }
                    }
                } else if (eo.FieldType == CodeTypeDef.FormField.DateTime) {
                    sb.Append("<input type=\"text\" " + id_name_val + "   onclick=\"jskitDateSelector.setMode('d');jskitDateSelector.open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.DateTime) {
                    sb.Append("<input type=\"text\" " + id_name_val + "   onclick=\"jskitDateSelector.setMode('dt');jskitDateSelector.open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.DropDownList) {
                    sb.Append("<select " + id_name_val + " >");
                    sb.Append("<option value=\"\">" + TxtDef.DDLTextEmpty + "</option>");
                    foreach (TProductAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<option value=\"" + opt.OptValue + "\" selected=\"selected\">" + opt.OptText + "</option>");
                            } else {
                                sb.Append("<option value=\"" + opt.OptValue + "\">" + opt.OptText + "</option>");
                            }
                        }
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.MultiText) {
                    sb.Append("<textarea cols=\"40\" rows=\"5\" " + name + " >" + val + "</textarea>");
                } else if (eo.FieldType == CodeTypeDef.FormField.Radio) {
                    sb.Append("<input type=\"radio\" " + name + " value=\"\" />" + TxtDef.DDLTextEmpty + "");
                    foreach (TProductAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<input type=\"radio\" " + name + " value=\"" + opt.OptValue + "\" checked=\"checked\" />" + opt.OptText + "");
                            } else {
                                sb.Append("<input type=\"radio\" " + name + " value=\"" + opt.OptValue + "\" />" + opt.OptText + "");
                            }
                        }
                    }
                } else if (eo.FieldType == CodeTypeDef.FormField.TextBox) {
                    sb.Append("<input type=\"text\" " + id_name_val + " />");
                } else {
                    sb.Append("<input type=\"text\" " + id_name_val + " />");
                }
                sb.Append("</td>");
                sb.Append("<td class=\"product_atl_form_desc\">" + eo.AtlDesc + "</td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            return sb.ToString();
        }
        #endregion
        #region System Atl
        /// <summary>
        /// 获取对象扩展属性的编辑面板
        /// </summary>
        /// <param name="rCategoryKey"></param>
        /// <param name="rItemKey"></param>
        /// <returns></returns>
        public static string LoadItemAtlEditForm(String rCategoryKey, String rItemKey,String rOwnerKey,UserPower rPower) {
            IItemBiz biz = BizFactory.Get<IItemBiz>();
            IList<VSysAtlEO> list = biz.LoadSysAtlByCategory(rCategoryKey, rPower);
            IList<VSysAtlOptionsEO> optList = biz.LoadSysAtlOptionsByCategory(rCategoryKey);
            IList<TItemAtlDataEO> dataList = new List<TItemAtlDataEO>();
            String hql = "";
            if (!String.IsNullOrEmpty(rItemKey)) {
                hql = " from TItemAtlDataEO eo where eo.ItemKey='" + rItemKey + "' ";
                dataList = biz.Find<TItemAtlDataEO>(hql);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"product_atl_form_table\">");
            foreach (VSysAtlEO eo in list) {
                sb.Append("<tr>");
                sb.Append("<td class=\"item_atl_form_name\">" + eo.AtlName + "：</td>");
                sb.Append("<td class=\"item_atl_form_field\">");
                String val = eo.DefaultValue;
                String rkey = null;
                String jsHd = "j" + eo.AtlKey;
                foreach (TItemAtlDataEO data in dataList) {
                    if (data.AtlKey == eo.AtlKey) {
                        val = data.DataValue;
                        rkey = (data.RefItemKey == null) ? "" : data.RefItemKey;
                    }
                }
                String id_name_val = " id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" value=\"" + val + "\" ";
                String name = " name=\"" + eo.AtlKey + "\" ";
                if (eo.FieldType == CodeTypeDef.FormField.CheckBox) {
                    sb.Append("<input type=\"checkbox\" " + name + " value=\"\" />" + TxtDef.DDLTextEmpty + "");
                    foreach (VSysAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<input type=\"checkbox\" " + name + " value=\"" + opt.OptValue + "\" checked=\"checked\" />" + opt.OptText + "");
                            } else {
                                sb.Append("<input type=\"checkbox\" " + name + " value=\"" + opt.OptValue + "\" />" + opt.OptText + "");
                            }
                        }
                    }
                } else if (eo.FieldType == CodeTypeDef.FormField.Date) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + "   onclick=\""+jsHd + ".setMode('d');"+jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.DateTime) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + "   onclick=\""+jsHd + ".setMode('dt');"+jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.YearMonth) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + "   onclick=\"" + jsHd + ".setMode('m');" + jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Year) {
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + " />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Month) {
                    sb.Append("<select " + id_name_val + " >");
                    sb.Append("<option value=\"\">" + TxtDef.DDLTextEmpty + "</option>");
                    for (int k = 1; k <= 12; k++) {
                        sb.Append("<option value=\"" + k + "\">" + k + "</option>");
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.DropDownList) {
                    sb.Append("<select " + id_name_val + " >");
                    sb.Append("<option value=\"\">" + TxtDef.DDLTextEmpty + "</option>");
                    foreach (VSysAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<option value=\"" + opt.OptValue + "\" selected=\"selected\">" + opt.OptText + "</option>");
                            } else {
                                sb.Append("<option value=\"" + opt.OptValue + "\">" + opt.OptText + "</option>");
                            }
                        }
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.MultiText) {
                    sb.Append("<textarea  class=\"item_atl_form_field_mtxt\" " + name + " >" + val + "</textarea>");
                } else if (eo.FieldType == CodeTypeDef.FormField.Radio) {
                    sb.Append("<input type=\"radio\" " + name + " value=\"\" />" + TxtDef.DDLTextEmpty + "");
                    foreach (VSysAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<input type=\"radio\" " + name + " value=\"" + opt.OptValue + "\" checked=\"checked\" />" + opt.OptText + "");
                            } else {
                                sb.Append("<input type=\"radio\" " + name + " value=\"" + opt.OptValue + "\" />" + opt.OptText + "");
                            }
                        }
                    }
                } else if (eo.FieldType == CodeTypeDef.FormField.TextBox) {
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + " />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Boolean) {
                    sb.Append("<input type=\"radio\" " + name + " value=\"1\" checked=\"checked\" />" + TxtDef.TRUE + "");
                    sb.Append("<input type=\"radio\" " + name + " value=\"0\" />" + TxtDef.FALSE + "");
                } else if (eo.FieldType == CodeTypeDef.FormField.Item) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, rkey, "Ws/_Item.aspx?act=list&ck=" + eo.RefKey, "item_atl_form_field_stxt"));
                } else if (eo.FieldType == CodeTypeDef.FormField.User) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, rkey, "Ws/_User.aspx?mode=rddl", "item_atl_form_field_stxt"));
                } else if (eo.FieldType == CodeTypeDef.FormField.Dept) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, rkey, "Ws/_Dept.aspx", "item_atl_form_field_stxt"));
                } else {
                    sb.Append("<input class=\"item_atl_form_field_stxt\" type=\"text\" " + id_name_val + " />");
                }
                sb.Append("</td>");
                sb.Append("<td class=\"item_atl_form_desc\">" + eo.AtlDesc + "</td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            return sb.ToString();
        }
        private static string BuildRDdlAtlItemHTML(String rAtlKey,String rVal,String rRefKey,String rWsUrl,String rTxtFeildCss) {
            StringBuilder sb = new StringBuilder();
            String jsHd = "j" + rAtlKey;//JskitDrowDownList 的句柄
            String tId = rAtlKey;
            String vId = rAtlKey + "_ref";
            rVal = (rVal == null) ? "" : rVal;
            rRefKey = (rRefKey == null) ? "" : rRefKey;
            sb.Append("<input  atl_type=\"item\" class=\"" + rTxtFeildCss + "\" type=\"text\" name=\"" + tId + "\" id=\"" + tId + "\" value=\"" + rVal + "\" />");
            sb.Append("<input type=\"hidden\" name=\"" + vId + "\" id=\"" + vId + "\" value=\"" + rRefKey + "\" />");
            sb.Append("<script type=\"text/javascript\">");
            sb.Append("var " + jsHd + " = new JskitRichDropDownList(\"" + jsHd + "\");");
            sb.Append(jsHd + ".setEmptySelectText(\"--\");");
            sb.Append(jsHd + ".deployTree(\"" + tId + "\", \"" + vId + "\", \"" + rWsUrl + "\");");
            sb.Append("</script>");
            return sb.ToString();
        }
        public static string LoadItemAtlQueryForm(String rCategoryKey, ref IList<String> rAtlKeyList, UserPower rPower) {
            IItemBiz biz = BizFactory.Get<IItemBiz>();
            IList<VSysAtlEO> list = biz.LoadSysAtlByCategory(rCategoryKey,rPower);

            IList<VSysAtlOptionsEO> optList = biz.LoadSysAtlOptionsByCategory(rCategoryKey);
            StringBuilder sb = new StringBuilder();
            sb.Append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"item_atl_qform\">");
            int q_count = 0;
            for (int i=0;i<list.Count;i++){
                VSysAtlEO eo = list[i];
                rAtlKeyList.Add(eo.AtlKey);
                if (eo.IsQueriable == 0) continue;
                q_count++;
                sb.Append("<tr class=\"item_atl_qform_row" + (q_count % 2) + "\">");
                sb.Append("<td class=\"item_atl_qform_name\">" + eo.AtlName + "：</td>");
                sb.Append("<td class=\"item_atl_qform_field\">");
                String val = eo.DefaultValue;
                String id_name_val = " id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" value=\"" + val + "\" ";
                String name = " name=\"" + eo.AtlKey + "\" ";
                String jsHd = "j"+eo.AtlKey;      
                if (eo.FieldType == CodeTypeDef.FormField.CheckBox
                    || eo.FieldType == CodeTypeDef.FormField.Radio
                    || eo.FieldType == CodeTypeDef.FormField.DropDownList) {
                    sb.Append("<select " + id_name_val + " atl_type=\"ddl\" />");
                    sb.Append("<option value=\"\" /></option>");
                    foreach (VSysAtlOptionsEO opt in optList) {
                        if (opt.AtlKey == eo.AtlKey) {
                            if (opt.OptValue == val) {
                                sb.Append("<option value=\"" + opt.OptValue + "\" selected=\"selected\" />" + opt.OptText + "</option>");
                            } else {
                                sb.Append("<option value=\"" + opt.OptValue + "\" />" + opt.OptText + "</option>");
                            }
                        }
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.MultiText
                    || eo.FieldType == CodeTypeDef.FormField.TextBox) {
                        sb.Append("<input atl_type=\"txt\" class=\"item_atl_qform_field_stxt\" type=\"text\" " + id_name_val + " value=\"" + val + "\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Boolean) {
                    sb.Append("<select " + id_name_val + " atl_type=\"ddl\" />");
                    sb.Append("<option value=\"\" /></option>");
                    if (val == "1") {
                        sb.Append("<option value=\"1\" selected=\"selected\" />" + TxtDef.TRUE + "</option>");
                        sb.Append("<option value=\"0\" />" + TxtDef.FAILED + "</option>");
                    } else {
                        sb.Append("<option value=\"1\" />" + TxtDef.TRUE + "</option>");
                        sb.Append("<option value=\"0\" selected=\"selected\" />" + TxtDef.FAILED + "</option>");
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.Date) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input atl_type=\"dt\" type=\"text\" id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" onclick=\"" + jsHd + ".setMode('d');" + jsHd + ".open(this,event)\" />");
                    sb.Append("<br/><input type=\"text\" id=\"" + eo.AtlKey + "2\"  name=\"" + eo.AtlKey + "2\" onclick=\"" + jsHd + ".setMode('d');" + jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.DateTime) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input  atl_type=\"dt\" type=\"text\" id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" onclick=\"" + jsHd + ".setMode('dt');" + jsHd + ".open(this,event)\" />");
                    sb.Append("<br/><input type=\"text\" id=\"" + eo.AtlKey + "2\"  name=\"" + eo.AtlKey + "2\" onclick=\"" + jsHd + ".setMode('dt');" + jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.YearMonth) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input  atl_type=\"dm\" type=\"text\" id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" onclick=\"" + jsHd + ".setMode('m');" + jsHd + ".open(this,event)\" />");
                    sb.Append("<br/><input type=\"text\" id=\"" + eo.AtlKey + "2\"  name=\"" + eo.AtlKey + "2\" onclick=\"" + jsHd + ".setMode('m');" + jsHd + ".open(this,event)\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Year) {
                    sb.Append("<script type=\"text/javascript\">var " + jsHd + "=new JskitDateSelector('" + jsHd + "');</script>");
                    sb.Append("<input  atl_type=\"month\" atl_type=\"year\" type=\"text\" id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\" size=\"4\" maxlength=\"4\" />");
                    sb.Append("--<input type=\"text\" id=\"" + eo.AtlKey + "2\"  name=\"" + eo.AtlKey + "2\" size=\"4\" maxlength=\"4\" />");
                } else if (eo.FieldType == CodeTypeDef.FormField.Month) {
                    sb.Append("<select atl_type=\"month\" id=\"" + eo.AtlKey + "\"  name=\"" + eo.AtlKey + "\">");
                    sb.Append("<option value=\"\"></option>");
                    for (int k = 1; k <= 12; k++) {
                        sb.Append("<option value=\"" + k + "\">" + k + "</option>");
                    }
                    sb.Append("</select>");
                    sb.Append("--<select id=\"" + eo.AtlKey + "2\"  name=\"" + eo.AtlKey + "2\" >");
                    sb.Append("<option value=\"\"></option>");
                    for (int k = 1; k <= 12; k++) {
                        sb.Append("<option value=\"" + k + "\">" + k + "</option>");
                    }
                    sb.Append("</select>");
                } else if (eo.FieldType == CodeTypeDef.FormField.Item) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, null, "Ws/_Item.aspx?act=list&ck=" + eo.RefKey,"item_atl_qform_field_stxt"));
                } else if (eo.FieldType == CodeTypeDef.FormField.User) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, null, "Ws/_User.aspx?mode=rddl", "item_atl_qform_field_stxt"));
                } else if (eo.FieldType == CodeTypeDef.FormField.Dept) {
                    sb.Append(BuildRDdlAtlItemHTML(eo.AtlKey, val, null, "Ws/_Dept.aspx", "item_atl_qform_field_stxt"));
                }
                sb.Append("</td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            return sb.ToString();
        }
        public static _SysAtlRefEO ParseRefEO(TSysAtlEO rAtl) {
            _SysAtlRefEO _eo = new _SysAtlRefEO();
            _eo.RefObjKey = "";
            _eo.RefObjName = "";
            IBiz biz = BizFactory.Get<IBiz>();
            if (rAtl != null) {
                try {
                    _eo.RefObjKey = rAtl.RefKey;
                    if (rAtl.FieldType == CodeTypeDef.FormField.Item) {
                        TItemEO eo = biz.Load<TItemEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.ItemName;
                    } else if (rAtl.FieldType == CodeTypeDef.FormField.User) {
                        TSysUserEO eo = biz.Load<TSysUserEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.RealName;
                    } else if (rAtl.FieldType == CodeTypeDef.FormField.Dept) {
                        TSysDeptEO eo = biz.Load<TSysDeptEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.DeptName;
                    }
                } catch (Exception ex) {
                    log.Error("解析属性关联对象数据时出现异常:" + ex.Message);
                }
            }
            return _eo;
        }
        public static _SysAtlRefEO ParseRefEO(VSysAtlEO rAtl) {
            _SysAtlRefEO _eo = new _SysAtlRefEO();
            IBiz biz = BizFactory.Get<IBiz>();
            _eo.RefObjKey = "";
            _eo.RefObjName = "";
            if (rAtl != null) {
                try {
                    _eo.RefObjKey = rAtl.RefKey;
                    if (rAtl.FieldType == CodeTypeDef.FormField.Item) {
                        TItemEO eo = biz.Load<TItemEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.ItemName;
                    } else if (rAtl.FieldType == CodeTypeDef.FormField.User) {
                        TSysUserEO eo = biz.Load<TSysUserEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.RealName;
                    } else if (rAtl.FieldType == CodeTypeDef.FormField.Dept) {
                        TSysDeptEO eo = biz.Load<TSysDeptEO>(rAtl.RefKey);
                        _eo.RefObjName = eo.DeptName;
                    }
                } catch (Exception ex) {
                    log.Error("解析属性关联对象数据时出现异常:" + ex.Message);
                }
            }
            return _eo;
        }


        #endregion

        #region 通用方法
        /// <summary>
        /// DateTime? to String
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static String ParseNullDt2String(DateTime? dt) {
            try {
                return Convert.ToDateTime(dt).ToString("yyyy-MM-dd hh:mm:ss");
            } catch {
                return "";
            }
        }
        /// <summary>
        /// 字符串列表转换成逗号分隔的字符串
        /// </summary>
        /// <param name="rList"></param>
        /// <returns></returns>
        public static String ConvertList2String(IList<String> rList) {
            if (rList == null || rList.Count == 0) return "";
            String opts = "";
            for (int i = 0; i < rList.Count; i++) {
                String opt = rList[i];
                if (i > 0) opts += ",";
                opts += opt;
            }
            return opts;
        }
        #endregion

        #region 日历显示
        /// <summary>
        /// 构造日历显示的HTML代码
        /// </summary>
        /// <param name="rCurDt">当前日期</param>
        /// <param name="rMode">模式，0：周历，1：月历</param>
        /// <param name="rFirstDt">开始日期</param>
        /// <param name="rLastDt">结束日期</param>
        /// <returns></returns>
        public static String BuildCalendarHtmlCode(DateTime rCurDt,Int32 rMode, ref DateTime rFirstDt,ref DateTime rLastDt) {
            IList<DateTime> wl = new List<DateTime>();
            if (rMode == 0) {//周历
                int dayOfWeek = (Int32)rCurDt.DayOfWeek;
                rFirstDt = rCurDt.AddDays(-14 - dayOfWeek);
                rLastDt = rCurDt.AddDays(14 + 6 - dayOfWeek);
                wl.Add(rCurDt.AddDays(-14));
                wl.Add(rCurDt.AddDays(-7));
                wl.Add(rCurDt);
                wl.Add(rCurDt.AddDays(7));
                wl.Add(rCurDt.AddDays(14));
            } else {//月历
                rFirstDt = Convert.ToDateTime(rCurDt.ToString("yyyy-MM-1"));
                rLastDt = Convert.ToDateTime(rCurDt.AddMonths(1).ToString("yyyy-MM-1")).AddDays(-1);
                //当月的天数
                int firstWof = (int)rFirstDt.DayOfWeek;
                //周数
                int weeks = Convert.ToInt32(Math.Ceiling(rLastDt.Day / 7.0));
                for (int i = 0; i < weeks; i++) {
                    wl.Add(rFirstDt.AddDays(i * 7));
                }
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("<table cellspacing=\"0\" cellpadding=\"0\" class=\"calendar\">");
            sb.Append("<tr>");
            sb.Append("<th class=\"cal_hd_empty\">&nbsp;</th>");
            for (int i = 0; i < 7; i++) {
                if (i == (int)rCurDt.DayOfWeek) {
                    sb.Append("<th class=\"cal_hd_current\">");
                } else if (i == 0 || i == 6) {
                    sb.Append("<th class=\"cal_hd_weekend\">");
                } else {
                    sb.Append("<th class=\"cal_hd_normal\">");
                }
                sb.Append(TxtDef.Calendar.WeekDayName[i] + "</th>");
            }
            sb.Append("</tr>");
            int year = rCurDt.Year;
            Boolean sameWeek = false;
            for (int i = 0; i < wl.Count; i++) {
                sameWeek = (DateUtil.WeekOfYear(wl[i]) == DateUtil.WeekOfYear(rCurDt));
                sb.Append("<tr>");
                if (sameWeek) {
                    sb.Append("<td class=\"cal_week_no_current\">");
                } else {
                    sb.Append("<td class=\"cal_week_no\">");
                }
                sb.Append("<a class=\"cal_week_link\" href=\"Admin/Calendar/List.aspx?dt1=" + wl[i].AddDays(0 - Convert.ToInt32(wl[i].DayOfWeek)).ToShortDateString() + "&dt2=" + wl[i].AddDays(6 - Convert.ToInt32(wl[i].DayOfWeek)).ToShortDateString() + "\">" + DateUtil.WeekOfYear(wl[i]) + "</a>");
                sb.Append("</td>");
                for (int j = 0; j < 7; j++) {
                    DateTime _dt = wl[i].AddDays(j - Convert.ToInt32(wl[i].DayOfWeek));
                    sb.Append("<td valign=\"top\" ");
                    if (sameWeek && j == (int)rCurDt.DayOfWeek) {
                        sb.Append(" class=\"cal_cell_today\" ");
                    } else if (j == 0) {
                        sb.Append(" class=\"cal_cell_sun\" ");
                    } else if (j == 6) {
                        sb.Append(" class=\"cal_cell_sat\" ");
                    } else {
                        sb.Append(" class=\"cal_cell_normal\" ");
                    }
                    sb.Append(">");
                    if (_dt.Month == rCurDt.Month) {
                        sb.Append("<div class=\"cal_cell_date\">");
                    } else {
                        sb.Append("<div class=\"cal_cell_date_out\">");
                    }
                    sb.Append("<a href=\"Admin/Calendar/List.aspx?dt1=" + _dt.ToShortDateString() + "&dt2=" + _dt.ToShortDateString() + "\">");
                    if (_dt.Day == 1) {
                        sb.Append(_dt.Month + "月," + _dt.Day);
                    } else {
                        sb.Append(_dt.Day);
                    }
                    if (ChDate.GetDay(_dt) == "初一") {
                        sb.Append("<span>(" + ChDate.GetMonth(_dt) + ChDate.GetDay(_dt) + "," + ChDate.GetSolarTerm(_dt) + ")</span>");
                    } else {
                        sb.Append("<span>(" + ChDate.GetDay(_dt) + "," + ChDate.GetSolarTerm(_dt) + ")</span>");
                    }
                    sb.Append("：</a>");
                    sb.Append("</div>");
                    sb.Append("<div id=\"cell_" + _dt.ToString("yyyy_MM_dd") + "\"></div>");
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }
            sb.Append("</table>");
            return sb.ToString();
        }
        #endregion
    }
}
